package com.api.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class EmailUtil extends Authenticator {
    static Logger logger =  LoggerFactory.getLogger("email");


    private static final String SEND_ENCODING_LAYOUT ="text/html;charset=utf-8";//发送邮件的编码格式

    //gmail邮箱的TLS方式
    private static void gmailtls(Properties props) {
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        props.put("mail.debug", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");
    }

    /*
     * 通过gmail邮箱发送邮件
     */
    public static void gmailSender (String email,String content,String subject) {

        // Get a Properties object
        Properties props = new Properties();
        //选择ssl方式
        gmailtls(props);

        final String username = "bounsteam@gmail.com";//gmail邮箱
        final String password = "BounteeGmail";//密码
        Session session = Session.getDefaultInstance(props,
                new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });
        // -- Create a new message --
        Message msg = new MimeMessage(session);
        // -- Set the FROM and TO fields --
        try {
            msg.setFrom(new InternetAddress(username));
            msg.setSubject(subject);
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(email));
            msg.setContent(  content ,SEND_ENCODING_LAYOUT);
//            msg.setText(prettyRegisterLayout("2小时",MAIL_ORGANIZATION,"https://www.xxxx.com/user/register/8asc824jnd741n2c"));
            msg.setSentDate(new Date());
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
        }



        logger.info("Message sent to " + email +" content" + content);
    }

    public static void main(String[] args) {
        String email = "<p>You are almost there! Please find the four-digit number below.</p>" +
                "<p>Please input the number on the singup page and proceed to complete registration.</p>" +
                "<br/>"+
                "<h1>Code: +"+"1234"+"<h1/>" +
                "<br/>"+
                "<br/>"+
                "<br/>"+
                "<h1>Bountee<h1>";
        gmailSender("wanghuiwen312@sina.com",email,"subject");
    }

}
